/**
 * 2017年11月9日
 */
package com.alibaba.study.dynamicproxy.dynamic;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.alibaba.study.dynamicproxy.Hello;
import com.alibaba.study.dynamicproxy.common.HelloService;
import com.alibaba.study.dynamicproxy.simple.StaticProxy;

/**
 * @author Alex
 *
 */
public class DynamicProxyDriver {

	public static void main(String[] args) {
		Hello hello = getService(false);
		System.out.println(hello.sayHello(" Alex "));
	}
	static Hello getService(boolean flag){
		
		if(flag){
			return (Hello)Proxy.newProxyInstance(DynamicProxyDriver.class.getClassLoader(), new Class[]{Hello.class}, new InvocationHandler(){
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					//System.out.println(proxy.getClass());
					System.out.println(method);
					System.out.println(args);
					return " From dynamic Proxy , Hello  " + args[0];
				}
			});
		}else{
			return (Hello)Proxy.newProxyInstance(DynamicProxyDriver.class.getClassLoader(), new Class[]{Hello.class},getHandler());
		}
	}
	static InvocationHandler getHandler(){
		return new Handler();
	}
	static class Handler implements InvocationHandler{
		static Hello real = new HelloService();
//		static Hello staticProxy = new StaticProxy(real);
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			//System.out.println(proxy.getClass());
			System.out.println(method);
			System.out.println(args);
			return real.sayHello((String)args[0]);
//			return " From dynamic Proxy , Hello  " + args[0];
		}
		
	}
	
}
